package com.example.hm_dtfkz.util;

import com.android.base.ui.base.BaseEntity;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * FileName: JsonUtil
 * Author: admin
 * Date: 2021/11/5 15:33
 * Description:
 */
public class JsonUtil {

    /**
     * json串转实体类对象
     *
     * @param response
     * @param entity
     * @return
     */
    public static BaseEntity fromJson(String response, BaseEntity entity) {
        BaseEntity baseEntity = entity;
        baseEntity = new Gson().fromJson(response, baseEntity.getClass());
        return baseEntity;
    }

    /**
     * 解析单个Key
     *
     * @param response
     * @param key
     * @return
     */
    public static String parsingKey(String response,String key) {
        String value = "";
        try {
            JSONObject jsonObject = new JSONObject(response);
            value = jsonObject.optString(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 解析单个Key
     *
     * @param response
     * @param key
     * @return
     */
    public static int parsKey(String response,String key) {
        int code = 0;
        try {
            JSONObject jsonObject = new JSONObject(response);
            code = jsonObject.optInt(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 解析单个Key
     *
     * @param response
     * @param key
     * @return
     */
    public static Double parsKeyDouble(String response, String key) {
        double code = 0.0;
        try {
            JSONObject jsonObject = new JSONObject(response);
            code = jsonObject.optDouble(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return code;
    }

}
